/**
 * 
 */
requirejs.config({
    baseUrl:'http://static.auoffice.com/static/js' ,
    waitSeconds: 0,
    paths: {
    	jquery:'libs/jquery.min',
    	validate:'libs/validate/jquery.validate.min',
        datatables: 'libs/dataTables/jquery.dataTables.min',
        btdatatables: 'libs/dataTables/dataTables.bootstrap.min',
        //plugins
        base: 'common/base',
    },
    shim: {
    	'validate': {
    		deps: ['jquery'],
    		exports: 'validate'
    	},
        'datatables': {
            deps: ['jquery'],
            exports: 'datatables'
        },
        'btdatatables': {
            deps: ['jquery'],
            exports: 'btdatatables'
        }, 
    }
});

require([
    'jquery',
 	'common/base',
 	'validate',
 	'datatables',
 	'btdatatables',
],function($,base) {
	var login_user = $("#login_user").attr("data-login_user");
    var table = $("#data_table").DataTable({
        "searching": true,
        "processing": true,
        "serverSide": true,
        "ordering": false,
        "deferRender": true,
        "ajax": {
            "url": '/account/user/list/',
            "type": "POST"
        },
        "columnDefs": [
            {
                "targets": 0,
                "data": null,
                "name": null,
                "searchable": false,
                "bSortable": false,
                "render": function (data, type, full) {
                    var html = '';
                    html += '<input type="checkbox" style="width:18px;height:18px" name="user_id" data-is_active="'+full.is_active+'" data-id="'+full.id+'"/>';
                    return html;
                }
            },
            {
            	"targets": 1,
            	"data": "username",
            	"name": "username",
            	"searchable": false,
            	"bSortable": false
            },
            {
            	"targets": 2,
            	"data": "first_name",
            	"name": "first_name",
            	"searchable": false,
            	"bSortable": false
            },
            {
            	"targets": 3,
            	"data": "mobile",
            	"name": "mobile",
            	"searchable": false,
            	"bSortable": false
            },
            {
            	"targets": 4,
            	"data": "email",
            	"name": "email",
            	"searchable": false,
            	"bSortable": false
            },
            {
            	"targets": 5,
            	"data": "user_type",
            	"name": "user_type",
            	"searchable": false,
            	"bSortable": false
            },
            {
            	"targets": 6,
            	"data": null,
            	"name": null,
            	"searchable": false,
            	"bSortable": false,
            	"render": function (data, type, full) {
            		var html = '<p class="text-center">'+full.is_active_desc+'</p>';
            		return html;
            	}
            },
            {
            	"targets": 7,
            	"data": "date_joined",
            	"name": "date_joined",
            	"searchable": false,
            	"bSortable": false
            },
        ],
        "initComplete": function () {
            var api = this.api();
            var column = api.column(6);
            var select = $('<select class="form-control" id="user_status"><option value="">--用户状态--</option></select>')
            .appendTo($(column.header()).empty() )
            .on( 'change', function (){
                var val = $.fn.dataTable.util.escapeRegex(
                    $(this).val()
                );
                $("#all").prop("checked",false);
                column.search( val ? '^'+val+'$' : '', true, false ).draw();
            });
            select.append(user_status());
        },
        "oLanguage": {
            "sLengthMenu": '每页显示 _MENU_条 &nbsp;',
            "sZeroRecords": "没有找到符合条件的数",
            "sProcessing": "加载中...",
            "sInfo": "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
            "sInfoEmpty": "木有记录",
            "sInfoFiltered": "(从 _MAX_ 条记录中过滤)",
            "sSearch": "搜索：",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "«",
                "sNext": "»",
                "sLast": "尾页"
            }
        },
    });
    
    var user_status = function() {
        return  '<option value="0">已删除</option><option value="1">正常</option>';
    };  
    
    //datatables 行点击事件
    $("#data_table tbody").on('click','tr', function () {
    	var checked = $("td",this).find("input[type=checkbox]");
    	if ($(checked).is(':checked')){
    		$(checked).prop("checked",false);
    	}else{
    		$(checked).prop("checked",true);
    	}
    	var tr_len = $("#data_table tbody tr").find("input[type=checkbox]").length;
    	var check_len = $("#data_table tbody tr").find("input[type=checkbox]:checked").length;
    	if (tr_len == check_len){
    		$("#all").prop("checked",true);
    	}else{
    		$("#all").prop("checked",false);
    	}
    });
    
    //datatables 全选事件
    $("#all").click(function(){
    	if ($(this).is(':checked')){
    		$("#data_table tbody tr").find("input[type=checkbox]").prop("checked",true);
    	}else{
    		$("#data_table tbody tr").find("input[type=checkbox]").prop("checked",false);
    	}
    });
    
    //自定义验证规则
	$.validator.addMethod("emailMobile", function(value, element) {   
    	var mobile_reg = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;
    	var email_reg = /^[a-zA-Z0-9][\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
    	return this.optional(element) || (mobile_reg.test(value)||email_reg.test(value));
    }, "请输入正确的手机号码或邮箱");
    
    //点击添加用户按钮
    $(".add").click(function(){
    	Add({});
    });
    //修改用户
    $(".update").click(function(){
    	var len = $("[name=user_id]:checked").length;
    	if (len != 1){
    		base.layui.alert("信息","请选择一行数据编辑");
    		return;
    	}
    	var _user_id = $("[name=user_id]:checked").attr("data-id");
    	if (_user_id == login_user){
    		base.layui.alert("信息","不能操作当前用户");
    		return;
    	}
    	var o = "/account/user/edit/?user_id="+_user_id;
    	var l = "修改用户信息";
    	base.contabs.addtab(o,l,window.document.location.pathname);
    });
    //查看用户
    $(".view").click(function(){
    	var len = $("[name=user_id]:checked").length;
    	if (len != 1){
    		base.layui.alert("信息","请选择一行数据查看");
    		return;
    	}
    	var _user_id = $("[name=user_id]:checked").attr("data-id");
    	var o = "/account/user/detail/?user_id="+_user_id;
    	var l = "查看用户信息";
    	base.contabs.addtab(o,l,window.document.location.pathname);
    });
    //查看资源
    $(".view-resource").click(function(){
    	var len = $("[name=user_id]:checked").length;
    	if (len != 1){
    		base.layui.alert("信息","请选择一行数据查看");
    		return;
    	}
    	var _user_id = $("[name=user_id]:checked").attr("data-id");
    	var o = "/account/user/resource/?user_id="+_user_id;
    	var l = "查看用户资源";
    	base.contabs.addtab(o,l,window.document.location.pathname);
    });
    //查看功能
    $(".view-func").click(function(){
    	var len = $("[name=user_id]:checked").length;
    	if (len != 1){
    		base.layui.alert("信息","请选择一行数据查看");
    		return;
    	}
    	var _user_id = $("[name=user_id]:checked").attr("data-id");
    	var o = "/account/user/funcresource/?user_id="+_user_id;
    	var l = "查看用户功能";
    	base.contabs.addtab(o,l,window.document.location.pathname);
    });
    $(".delete").click(function(){
    	var len = $("[name=user_id]:checked").length;
    	if (len <= 0){
    		base.layui.alert("信息","请选择数据删除");
    		return;
    	}
    	var exist_active = false;
    	var _user_ids = []
    	$("[name=user_id]:checked").each(function(){
    		if($(this).attr("data-is_active") == "false"){
    			exist_active = true;
    			return false;
    		}
    		_user_ids.push($(this).attr("data-id"));
    	});
    	if (_user_ids.indexOf(login_user) > -1){
    		base.layui.alert("信息","不能操作当前用户");
    		return;
    	}
    	if(exist_active){
    		base.layui.alert("信息","请选择正常的用户删除");
    		return;
    	}
    	base.layui.confirm('警告', '确认删除选中的用户？',{"_user_ids":_user_ids}, _delUserCallback);
    });
    var _delUserCallback = function(arg){
    	base.services.post('account', 'deleteUser', {"user_ids":arg._user_ids.join(",")}, function(code, msg, data) {
    		if (code === base.services.CODE_SUCC) {
    			if($("#user_status").val() == ""){
    				$("[name=user_id]:checked").attr("data-is_active","false");
    				$("[name=user_id]:checked").closest("tr").each(function(){
    					$(this).children().eq(6).find("p").text("已删除");
    				});
    			}else{
    				callback();
    			}
    			base.layui.alert("成功信息","删除成功");
    		} else {
    			base.layui.alert("错误信息",msg);
    		}
    	});
    };
    $(".activate").click(function(){
    	var len = $("[name=user_id]:checked").length;
    	if (len <= 0){
    		base.layui.alert("信息","请选择数据删除");
    		return;
    	}
    	var exist_active = false;
    	var _user_ids = []
    	$("[name=user_id]:checked").each(function(){
    		if($(this).attr("data-is_active") == "true"){
    			exist_active = true;
    			return false;
    		}
    		_user_ids.push($(this).attr("data-id"));
    	});
    	if (_user_ids.indexOf(login_user) > -1){
    		base.layui.alert("信息","不能操作当前用户");
    		return;
    	}
    	if(exist_active){
    		base.layui.alert("信息","请选择已删除的用户激活");
    		return;
    	}
    	base.layui.confirm('警告', '确认激活选中的用户？',{"_user_ids":_user_ids}, _actUserCallback);
    });
    var _actUserCallback = function(arg){
    	base.services.post('account', 'activateUser', {"user_ids":arg._user_ids.join(",")}, function(code, msg, data) {
    		if (code === base.services.CODE_SUCC) {
    			if($("#user_status").val() == ""){
    				$("[name=user_id]:checked").attr("data-is_active","false");
    				$("[name=user_id]:checked").closest("tr").each(function(){
    					$(this).children().eq(6).find("p").text("正常");
    				});
    			}else{
    				callback();
    			}
    			base.layui.alert("成功信息","激活成功");
    		} else {
    			base.layui.alert("错误信息",msg);
    		}
    	});
    };
    var parent_layer;
	var Add = function(data){
		var add_html = base.tpls("auoffice/account/user/add",data);
		parent_layer = layer.open({
			type: 1,
			area : ['430px','400px'],
			skin: 'layui-layer-demo', //样式类名
			title: ['添加用户', 'font-weight: bold;'],
			closeBtn: 1, //不显示关闭按钮
			shift: 2,
			btn: ['提交','取消'],
			shadeClose: true, //开启遮罩关闭
			content: add_html,
			success: function (layero) {
			    var btn = layero.find('.layui-layer-btn');
			    btn.css('text-align', 'center');
			},
			btn1:function(index ,layerp){
				$("#signupForm").submit();
			},
			btn2:function(index ,layero){
				layer.close(index);
			}
		});
		
		
		//表单验证
		$("#signupForm").validate({
			rules:{
				firstname:{//昵称
					required:true,
					minlength:2,
					maxlength:16,
				},
				username:{//用户名
					required:true,
					minlength:7,
					maxlength:30,
					emailMobile:true,
					remote: {
                        url: '/account/checkusername/',
                        type: 'post',
                        dataType: 'json',
                        data: {
                        	username: function() {
                            return $( "input[name=username]" ).val();
                          }
                        }
                    }
				},
				password:{//密码
					required:true,
					minlength:6,
					maxlength:20,
				},
				confirm_password:{//确认密码
					required:true,
					equalTo:"#password"
				},
			},
			messages:{
				firstname:{
					required:"请输入昵称",
					minlength:"昵称长度为2-16个字符",
					maxlength:"昵称长度为2-16个字符"
				},
				username:{//用户名
					required:"请输入用户名",
					minlength:"用户名长度为7-30个字符",
					maxlength:"用户名长度为7-30个字符",
					emailMobile:"请输入正确的手机号码或邮箱",
					remote:"用户名已存在"
				},
				password:{
					required:"请输入密码",
					minlength:"密码长度为6-20个字符",
					maxlength:"密码长度为6-20个字符"
				},
				confirm_password:{
					required:"请再次输入密码",
					equalTo:"两次输入的密码不一致"
				}
			},
			submitHandler:function(){
				base.services.post('account', 'saveUser', $("#signupForm").serialize(), function(code, msg, data) {
					if (code === base.services.CODE_SUCC) {
						base.layui.alert("成功信息","保存成功",callback);
					} else {
						base.layui.alert("错误信息",msg);
					}
				});
			}
		});
	}
	
	var callback = function(){
		if (parent_layer){
			layer.close(parent_layer);
		}
		table.draw();
	}
	
});